package com.bw.home

import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.ToastUtils
import com.blankj.utilcode.util.TouchUtils
import com.bw.home.adapter.VideoAdapter
import com.bw.home.adapter.VideoTypeAdapter
import com.bw.home.entity.VideoEntityItem
import com.bw.home.entity.VideoTypeEntityItem
import com.bw.home.viewmodel.HomeViewModel
import com.example.common.base.StateType
import com.example.common.base.UiState
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class HomeFragment : Fragment() {
    
    private lateinit var viewModel: HomeViewModel
    private lateinit var videoTypeAdapter: VideoTypeAdapter
    private lateinit var videoAdapter: VideoAdapter


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewModel = ViewModelProvider(this)[HomeViewModel::class.java]
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_home, container, false)
    }
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        initViews()
        initObservers()
        loadData()
    }
    
    private fun initViews() {
        // 初始化RecyclerView和适配器  top栏
        videoTypeAdapter = VideoTypeAdapter()

        view?.findViewById<androidx.recyclerview.widget.RecyclerView>(R.id.recycler_view)?.apply {
            // 设置LayoutManager - 这是关键！
            layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
            adapter = videoTypeAdapter
        }

        // 设置适配器点击事件
        videoTypeAdapter.setOnItemClickListener { item ->
            // 处理视频类型选择
            onVideoTypeSelected(item)
        }

        //视频播放请求
        videoAdapter = VideoAdapter()
        view?.findViewById<RecyclerView>(R.id.recycler_video)?.apply {
            layoutManager= LinearLayoutManager(context, LinearLayoutManager.VERTICAL,false)
            adapter = videoAdapter
        }



        // 点击事件
        videoAdapter.setOnItemClickListener { videoItem ->
            ToastUtils.showLong(videoItem.title)
        }
    }

    private fun initObservers() {
        // 观察ViewModel状态变化
        lifecycleScope.launch {
            viewModel.state.collectLatest { state ->
                when (state) {
                    is UiState.OnSuccess<*> -> {
                        when (state.type) {
                            StateType.VIDEO_TYPE -> {
                                Log.d("TAG", "${state.data} ")
                                val videoTypes = state.data as? List<VideoTypeEntityItem>
                                videoTypes?.let {
                                    Log.d("HomeFragment", "收到数据: ${it.size} 条")
                                    videoTypeAdapter.setData(it)
                                    // 默认选中第一个
                                    if (it.isNotEmpty()) {
                                        videoTypeAdapter.setSelectedPosition(0)
                                    }
                                }
                            }

                            StateType.VIDEO_MAIN -> {
                                Log.d("视频列表", "${state.data} ")
                                val videoList = state.data as? List<VideoEntityItem>
                                videoList?.let {
                                    Log.d("HomeFragment", "收到数据: ${it.size} 条")
                                    videoAdapter.setData(it)

                                }
                            }

                            else -> {
                                Log.d("HomeFragment", "其他类型数据: ${state.data}")
                            }


                        }
                    }
                    is UiState.OnError -> {
                        // 处理错误
                        Log.e("HomeFragment", "Error: ${"接受失败"}")
                    }
                    is UiState.OnLoading -> {
                        // 显示加载状态
                        Log.d("HomeFragment", "Loading...")
                        showLoading()
                    }
                }
            }
        }
    }

    private fun loadData() {
        // 加载视频类型数据
        Log.d("HomeFragment", "开始加载数据")
        viewModel.getVideoType()
        viewModel.getVideoList("2",2, 10)
    }

    private fun onVideoTypeSelected(item: VideoTypeEntityItem) {
        // 处理视频类型选择
        Log.d("HomeFragment", "选择了: ${item.typename}")
        val position = videoTypeAdapter.currentList().indexOfFirst { it.id == item.id }  // 加上括号调用方法
        if (position != -1) {
            // 2. 加载对应视频数据
            viewModel.getVideoList(item.id.toString(), 2, 10)

            Log.d("HomeFragment", "选择了: ${item.typename}")
            Toast.makeText(context, "选择了: ${item.typename}", Toast.LENGTH_SHORT).show()
        }
    }

    private fun showError(message: String) {
        // 显示错误信息
        Toast.makeText(context, "错误: $message", Toast.LENGTH_LONG).show()
    }

    private fun showLoading() {
        // 显示加载状态
        Toast.makeText(context, "加载中...", Toast.LENGTH_SHORT).show()
    }
    override fun onDestroy() {
        super.onDestroy()
        videoAdapter.releaseAllPlayers() // 释放 Player 资源
    }
}